# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from .models import Article, ArticleLikeUser
from userModel.models import Collect
from commentModel.models import Comment, CommentLikeUer
from django.db.models import Count
from toolFunctions import response, validator, checkLogin
from django.core.exceptions import ObjectDoesNotExist
from django.forms.models import model_to_dict
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger


#   新增/修改文章
@checkLogin.check_login
def update_article(request):
    article_id = request.POST.get('article_id', '')
    title = request.POST.get('title')
    content = request.POST.get('content', '')
    picture = request.POST.get('picture')
    user_id = request.session.get('user_id')

    if request.method != 'POST':
        return response.fail('ERROR_RES_METHOD')

    if response.request_is_empty(title):
        return response.fail('', '标题不能为空！')

    if response.request_is_empty(picture):
        return response.fail('', '封面图片不能为空！')

    if not article_id:
        article = Article(title=title, content=content, picture=picture, user_id=user_id)
        article.save()
        return response.success(article.id)
    else:
        try:
            article = Article.objects.get(id=article_id)
            article.title = title
            article.content = content
            article.picture = picture
            article.status = 0
            article.save()
            return response.success(article.id)
        except ObjectDoesNotExist:
            return response.fail('', '该文章不存在')

    return response.fail()


#   文章详情
def article_detail(request):
    article_id = request.GET.get('article_id', '')

    if response.request_is_empty(article_id):
        return response.fail(message='文章编号不能为空')

    article = Article.objects.filter(id=article_id).first()
    if article is None:
        return response.fail(message='该文章不存在')

    if article.status != 1:
        return response.fail(message='该文章' + article.get_status_str())

    #   判断时候收藏/点赞过文章
    user_id = request.session.get('user_id', '')
    collect_id = ''
    like_id = ''
    if user_id:
        collect = Collect.objects.filter(user_id=user_id, article_id=article_id).first()
        if collect:
            collect_id = collect.id

        article_like_user = ArticleLikeUser.objects.filter(article_id=article_id, user_id=user_id).first()
        if article_like_user:
            like_id = article_like_user.id

    #   获取评论数量
    comment_count = Comment.objects.filter(article_id=article_id, parent_id='' or 0 or None).aggregate(comment_count=Count('id'))['comment_count']

    #   获取点赞数量
    like_count = ArticleLikeUser.objects.filter(article_id=article_id).aggregate(count=Count('id'))['count']

    author = article.user
    res = model_to_dict(article)
    res['user'] = {
        "username": author.username,
        "head_img": author.head_img,
        "id": author.id
    }
    res["collect_id"] = collect_id
    res["comment_count"] = comment_count
    res['like_count'] = like_count
    res['like_id'] = like_id

    return response.success(res)


#   文章列表
def article_list(request):
    pageNo = request.GET.get('pageNo', 1)
    pageSize = request.GET.get('pageSize', 15)

    res = {}
    articles = Article.objects.filter(status=1).order_by("-id")
    paginator = Paginator(articles, pageSize)
    res['total'] = paginator.count

    try:
        list = paginator.page(pageNo)
    except PageNotAnInteger:
        list = paginator.page(1)
    except EmptyPage:
        list = []

    arr_list = []
    for item in list:
        dict_item = model_to_dict(item, exclude=['content'])
        dict_item['create_time'] = item.create_time.strftime("%Y-%m-%d %H:%M:%S")
        dict_item['update_time'] = item.update_time.strftime("%Y-%m-%d %H:%M:%S")

        author = item.user
        dict_item['user'] = {
            "username": author.username,
            "head_img": author.head_img,
            "id": author.id
        }

        arr_list.append(dict_item)

    res['items'] = arr_list

    return response.success(res)


#   文章点赞
@checkLogin.check_login
def article_like(request):
    user_id = request.session.get('user_id')
    article_id = request.GET.get('article_id', '')
    like_id = request.GET.get('like_id', '')

    #   取消赞
    if like_id:
        article_like_user = ArticleLikeUser.objects.filter(id=like_id, user_id=user_id).first()
        if article_like_user:
            article_like_user.delete()
            return response.success('取消赞成功')
        else:
            return response.fail('', '您并未点赞此文章')

    #   点赞
    if not article_id:
        return response.fail(message='文章编号不能为空')

    article = Article.objects.filter(id=article_id).first()
    if article is None:
        return response.fail(message='文章不存在')

    if article.user.id == user_id:
        return response.fail(message='不能点赞自己的文章哦')

    article_like_user = ArticleLikeUser(article_id=article_id, user_id=user_id)
    article_like_user.save()

    return response.success(article_like_user.id)


#   文章收藏
@checkLogin.check_login
def article_collect(request):
    user_id = request.session.get('user_id')
    article_id = request.GET.get('article_id', '')
    collect_id = request.GET.get('collect_id', '')

    if collect_id:      # 取消收藏
        collect = Collect.objects.filter(id=collect_id, user_id=user_id).first()
        if collect:
            collect.delete()
            return response.success('取消收藏成功')
        else:
            return response.fail('', '您并未收藏此文章')

    # 收藏
    if not article_id:
        return response.fail(message='文章编号不能为空')

    article = Article.objects.filter(id=article_id).first()
    if (article is None) or article.status == -1:
        return response.fail(message='文章不存在')

    collect = Collect(article_id=article_id, user_id=user_id)
    collect.save()
    return response.success(collect.id)


#   文章评论列表
def article_comments(request):
    pageNo = request.GET.get('pageNo', 1)
    pageSize = request.GET.get('pageSize', 15)
    article_id = request.GET.get('article_id', '')
    user_id = request.session.get('user_id', '')

    if validator.is_empty(article_id):
        return response.fail(message='文章编号不能为空')

    res = {}
    comments = Comment.objects.filter(status=1, article_id=article_id).order_by("-create_time")
    paginator = Paginator(comments, pageSize)
    res['total'] = paginator.count

    try:
        list = paginator.page(pageNo)
    except PageNotAnInteger:
        list = paginator.page(1)
    except EmptyPage:
        list = []

    arr_list = []
    for item in list:
        dict_item = model_to_dict(item)
        dict_item['create_time'] = item.create_time.strftime("%Y-%m-%d %H:%M:%S")
        dict_item['update_time'] = item.update_time.strftime("%Y-%m-%d %H:%M:%S")
        #   获取点赞数量以及用户是否点赞
        comment_like_user = CommentLikeUer.objects.filter(comment_id=dict_item['id'])
        dict_item['like_count'] = comment_like_user.values().count()
        dict_item['is_like'] = 0
        if user_id:
            dict_item['is_like'] = 0 if (comment_like_user.filter(user_id=user_id).first() is None) else 1
        #   获取评论人信息
        item_user = item.user
        dict_item['user'] = {
            'username': item_user.username,
            'id': item_user.id,
            'head_img': item_user.head_img
        }
        #   获取点评的评论信息
        if item.parent:
            itemParent = item.parent
            dict_item['parent'] = {
                'status': itemParent.status,
                'content': itemParent.content,
                'id': itemParent.id,
                'article': itemParent.article_id,
                'user': {
                    'username': itemParent.user.username,
                    'id': itemParent.user.id,
                    'head_img': itemParent.user.head_img
                }
            }
        else:
            dict_item['parent'] = ''

        arr_list.append(dict_item)

    res['items'] = arr_list

    return response.success(res)


#   文章发布
@checkLogin.check_login
def article_publish(request):
    user_id = request.session.get('user_id')
    article_id = request.POST.get('article_id', '')

    if not article_id:
        return response.fail(message='文章编号不能为空')

    article = Article.objects.filter(id=article_id).first()
    if article is None:
        return response.fail(message='文章不存在')

    if (user_id != article.user.id) or (article.status != 0):
        return response.fail(message='没有权限')

    article.status = 1
    article.save()

    return response.success()


#   文章撤销
@checkLogin.check_login
def article_unpublish(request):
    user_id = request.session.get('user_id')
    article_id = request.POST.get('article_id', '')

    if not article_id:
        return response.fail(message='文章编号不能为空')

    article = Article.objects.filter(id=article_id).first()
    if article is None:
        return response.fail(message='文章不存在')

    if (user_id != article.user.id) or (article.status != 1):
        return response.fail(message='没有权限')

    article.status = 0
    article.save()

    return response.success()


#   文章删除
@checkLogin.check_login
def article_delete(request):
    user_id = request.session.get('user_id')
    article_id = request.POST.get('article_id', '')

    if not article_id:
        return response.fail(message='文章编号不能为空')

    article = Article.objects.filter(id=article_id).first()
    if article is None:
        return response.fail(message='文章不存在')

    if user_id != article.user.id:
        return response.fail(message='没有权限')

    article.status = -1
    article.save()

    return response.success()


#   获取推荐文章
def get_article_recommend(request):
    count = 3       # 数量

    res = []
    articles = Article.objects.filter(status=1).order_by('-create_time')[0:count]

    for item in articles:
        dict_item = model_to_dict(item, exclude=['content'])

        author = item.user
        dict_item['user'] = {
            "username": author.username,
            "head_img": author.head_img,
            "id": author.id
        }

        res.append(dict_item)

    return response.success(res)





